<template>
  <div class="emp-detail">
    <Form :label-width="100" :model="detailList" :rules="ruleValidate" ref="detailRef">
      <Row type="flex">
        <template v-for="key in keys">
          <Col span="24" :key="key">
            <Form-item :prop="key" :label="$t(`module.employee.${key}`)" :key="key">
              <!-- <div v-if="isDate(key)">
                <DatePicker
                  :disabled="!isEdit"
                  v-model="detailList[key]"
                  type="date"
                />
              </div>-->
              <div v-if="key == 'startTime'">
                <DatePicker
                  @on-change="onStartDateChange"
                  :options="startDateOptions"
                  :disabled="!isEdit"
                  v-model="detailList[key]"
                  type="date"
                  :transfer="true"
                  :editable="false"
                  :clearable="false"
                  placement="bottom-end"
                  style="width: 100%;"
                  
                />
              </div>
              <div v-else-if="key == 'endTime'">
                <DatePicker
                  @on-change="onEndDateChange"
                  :options="endDateOptions"
                  :disabled="!isEdit"
                  v-model="detailList[key]"
                  :placeholder="$t('module.employee.permanent')"
                  :editable="false"
                  :clearable="false"
                  type="date"
                  :transfer="true"
                  placement="bottom-end"
                  style="width: 100%;"
                  
                />
              </div>
              <div v-else-if="key === 'enabled'">
                <i-switch
                  :disabled="!isEdit"
                  v-model="detailList[key]"
                  size="large"
                  :true-value="1"
                  :false-value="0"
                >
                  <span slot="open">{{$t('common.enable')}}</span>
                  <span slot="close">{{$t('common.disable')}}</span>
                </i-switch>
              </div>
              <div v-else-if="key === 'mainPostFlag'">
                <i-switch
                  :disabled="!isEdit"
                  v-model="detailList[key]"
                  size="large"
                  false-color="#13ce66"
                  true-color="#ff4949"
                  true-value="Y"
                  false-value="N"
                >
                  <span slot="open">{{$t('common.mainjob')}}</span>
                  <span slot="close">{{$t('common.partjob')}}</span>
                </i-switch>
              </div>
              <!-- <div v-else-if="key.includes('depart')">
                <Input
                  :disabled="!isEdit || key === 'departmentCode'"
                  @on-focus="focusHandler"
                  type="text"
                  v-model="detailList[key]"
                  :placeholder="`请选择${$t(`module.employee.${key}`)}`"
                />
              </div>-->
              <!-- <div v-else-if="key === 'description'">
                <Input
                  :disabled="!isEdit"
                  :rows="4"
                  :placeholder="`${$t(`module.employee.enter`)} ${$t(`module.employee.${key}`)}`"
                  type="textarea"
                  v-model="detailList[key]"
                />
              </div> -->
              <div
                v-else-if="key==='departmentDesc'||key==='positionDesc'||key==='supervisorName'"
                class="select-box"
              >
                <Input
                  v-model="detailList[key]"
                  :placeholder="$t('common.pleaseSelect')+$t(`module.employee.${key}`)"
                  disabled
                ></Input>
                <RPButton
                  v-if="isEdit"
                  optType="reset"
                  :text="$t('common.select')"
                  style="borderRadius:0;"
                  @click="focusHandler(key)"
                />
              </div>
              <div v-else-if="key==='jobCodeDesc'">
                <Input
                  :disabled="true"
                  :placeholder="$t(`module.employee.jobCreated`)"
                  type="text"
                  v-model="detailList[key]"
                />
              </div>
              <div v-else>
                <Input
                  :disabled="!isEdit"
                  :placeholder="`${$t(`module.employee.enter`)} ${$t(`module.employee.${key}`)}`"
                  type="text"
                  v-model="detailList[key]"
                />
              </div>
              <!-- depart -->
            </Form-item>
          </Col>
        </template>
      </Row>
    </Form>
  </div>
</template>
<script>
import locales from "./locales.js";
import { modifyJobEmployee, forceModifyJobEmployee } from "@/api/employeeApi";
import { jobBase } from "./keys";
import SelectDepBridge from "@/components/common/SelectDepBridge.vue";
import SelectPosBridge from "@/components/common/SelectPosBridge.vue";
import SelectSupervisor from "./selectSupervisor.vue";
// 一天的毫秒数
const ONE_DAY = 86400000;
export default {
  name: "EmployeeJobDetail",
  mixins: [locales],
  data: () => ({
    canSetMainPost: true,
    detailList: {}
  }),
  props: {
    details: {
      type: Object,
      default: () => {}
    },
    type: {
      type: String,
      default: "look"
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    employeeNo: {
      type: String,
      default: ""
    },
    allRecords: { type: Array, default: [] },
    isSelected: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    actions() {
      const acts = [
        {
          text: this.$t("common.close"),
          handle: () => this.$emit("Close")
        }
      ];
      if (this.isEdit) {
        acts.unshift({
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => this.saveHandler(),
          loading: false
        });
      }

      return acts;
    },
    ruleValidate() {
      return {
        jobCode: [{ required: true, message: this.$t("module.employee.tip.jobcode"), trigger: "none" }],
        departmentDesc: [{ required: true, message: this.$t("module.employee.tip.deptDescr"), trigger: "blur" }],
        positionDesc: [{ required: true, message: this.$t("module.employee.tip.posnDescr"), trigger: "blur" }]
        // supervisorName: [{ required: true, message: this.$t("module.employee.tip.supervisorName"), trigger: "blur" }]
      };
    },
    keys() {
      return jobBase;
    },
    startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.detailList.endTime == "object") {
            // 日期是日期对象，如 new Date()
            return (
              (date && date.valueOf() < Date.now() - ONE_DAY) || date.valueOf() > _this.detailList.endTime.valueOf()
            );
          } else if (typeof _this.detailList.endTime == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.detailList.endTime.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];

      return {
        disabledDate(date) {
          if (typeof _this.detailList.startTime == "object") {
            // 生效日期是日期对象，如 new Date()
            // debugger

            return date && date.valueOf() < _this.detailList.startTime.valueOf();
          } else if (typeof _this.detailList.startTime == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.detailList.startTime.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    }
  },

  created() {
    this.$emit("SetPageWidth", 500);
    this.$emit("SetPageActions", this.actions);
  },

  watch: {
    details: {
      handler: function(val) {
        this.addDefultAttr(val);
        this.checkMainJob(val);
        // this.detailList = { ...val };
        this.detailList = Object.assign(this.details, {
          workplace:this.details?.description,
          company:this.details?.costCenterName,
          startTime: this.formatDateTime(this.details.startTime),
          endTime: this.details.endTime == null ? "" : this.formatDateTime(this.details.endTime)
        });
        if (this.type == "add") {
          this.$emit("SetTitle", this.$t(`module.employee.createJobEmp`));
        } else if (this.type == "edit") {
          this.$emit("SetTitle", this.$t(`common.edit`));
        } else {
          this.$emit("SetTitle", this.$t(`module.employee.chnDetail`));
        }
      },
      immediate: true
    }
  },
  mounted: function() {
    this.init();
  },
  methods: {
    init() {
      if (this.type == "add") {
        this.$emit("SetTitle", this.$t(`module.employee.createJobEmp`));
        this.detailList.startTime = new Date().toLocaleDateString();
        this.detailList.endTime = "2099-12-31";
      } else if (this.type == "edit") {
        this.$emit("SetTitle", this.$t(`common.edit`));
        this.detailList = Object.assign(this.details, {
          startTime: this.formatDateTime(this.details.startTime),
          endTime: this.details.endTime == null ? "" : this.formatDateTime(this.details.endTime)
        });
      } else {
        this.$emit("SetTitle", this.$t(`module.employee.chnDetail`));
        this.detailList = Object.assign(this.details, {
          startTime: this.formatDateTime(this.details.startTime),
          endTime: this.details.endTime == null ? "" : this.formatDateTime(this.details.endTime)
        });
      }
      this.detailList.workplace = this.details?.description;
      this.detailList.company = this.details?.costCenterName;
    },
    onStartDateChange(date) {
      this.detailList.startTime = date;
    },
    onEndDateChange(date) {
      this.detailList.endTime = date;
    },
    // 补零
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 格式化时间
    formatDateTime(date) {
      var time = new Date(Date.parse(date));
      time.setTime(time.setHours(time.getHours() + 8));
      var Y = time.getFullYear() + "-";
      var M = this.addZero(time.getMonth() + 1) + "-";
      var D = this.addZero(time.getDate()) + " ";
      var h = this.addZero(time.getHours()) + ":";
      var m = this.addZero(time.getMinutes()) + ":";
      var s = this.addZero(time.getSeconds());
      return Y + M + D;
    },
    checkMainJob({ id }) {
      let item,
        { allRecords } = this;
      for (let len = allRecords.length, i = len - 1; i >= 0; i--) {
        item = allRecords[i];
        if (item.mainPostFlag == "Y" && item.id !== id) {
          this.canSetMainPost = false;
          this.detailList.mainPostFlag = "N";
          break;
        }
      }
    },
    addDefultAttr(val) {
      const { employeeNo } = this;
      val.employeeNo = employeeNo;
      typeof val.enabled === "number" || (val.enabled = 1);
      val.mainPostFlag || (val.mainPostFlag = "N");
    },
    saveHandler() {
      this.$refs["detailRef"].validate(async valid => {
        if (valid) {
          try {
            this.actions[0].loading = true;
            this.formatDate(this.detailList);
            let changedMainPost = this.detailList.departmentDesc + "/" + this.detailList.positionDesc;
            await modifyJobEmployee(this.detailList).then(res => {
              if (res.data.changMainPostStatus) {
                this.$message.success(this.$t(`common.${this.detailList.id ? "updateSuccess" : "createSuccess"}`));
                this.$emit("Close", true);
              } else {
                new $confirm(
                  `确认继续操作？员工主职由"${res.data.originMainPost}"更新为"${
                    res.data.changedMainPost != null ? res.data.changedMainPost : changedMainPost
                  }",
                原主职更新为兼职`,
                  this
                )
                  .then(() => {
                    forceModifyJobEmployee(this.detailList).then(res => {
                      this.$message.success(
                        this.$t(`common.${this.detailList.id ? "updateSuccess" : "createSuccess"}`)
                      );
                      this.$emit("Close", true);
                    });
                  })
                  .catch(() => {
                    this.actions[0].loading = false;
                  });
              }
            });
          } catch (error) {
            this.actions[0].loading = false;
          }
        } else {
          // this.$message.error(this.$t("common.formValidateFailed"));
        }
      });
    },
    formatDate(data) {
      const { isDate } = this;
      Object.keys(data).forEach(key => {
        if (isDate(key) && !!data[key]) {
          data[key] = data[key].constructor.toString().includes("Date")
            ? new Date(data[key]).Format("yyyy-MM-dd")
            : data[key];
        }
      });
    },
    isShowKey(key) {
      return jobKeys.includes(key);
    },
    isDate(key) {
      return /Dt|Date/.test(key) || key === "startTime" || key === "endTime";
    },
    focusHandler(key) {
      switch (key) {
        case "departmentDesc":
          this.selectDep();
          break;
        case "positionDesc":
          this.selectPos();
          break;
        case "supervisorName":
          this.selectSup();
          break;
      }
    },
    selectDep() {
      const { $pageModal, deptHandler } = this;
      const props = {
        successHandler: deptHandler.bind(this)
      };
      new $pageModal(SelectDepBridge, { props }, reset => reset);
      this.eventer = event;
    },
    selectPos() {
      if (!this.detailList.departmentDesc) {
        this.$message.error({
          content: this.$t(`module.employee.tip.selectDep`),
          duration: 3
        });
      } else {
        const { $pageModal, deptHandler } = this;
        const props = {
          departmentCode: this.detailList.departmentCode
        };
        new $pageModal(SelectPosBridge, { props }, data => {
          if (data) {
            this.detailList.positionDesc = data.nodeName;
            this.detailList.positionCode = data.code;
            this.detailList.jobCodeDesc = data.jobCodeDesc || data.jobCode;
            this.detailList.jobCode = data.jobCode;
          }
        });
        this.eventer = event;
      }
    },
    selectSup() {
      if (!this.detailList.departmentDesc) {
        this.$message.error({
          content: this.$t(`module.employee.tip.selectDep`),
          duration: 3
        });
      } else {
        const { $pageModal } = this;
        const props = {
          departmentCode: this.detailList.departmentCode
        };
        new $pageModal(SelectSupervisor, { props }, data => {
          if (data) {
            this.detailList.supervisorName = data.name;
            this.detailList.supervisorEmployeeNo = data.employeeNo;
          }
        });
        this.eventer = event;
      }
    },
    deptHandler({ code, orgId, nodeName }, target) {
      let id = this.detailList.orgId;
      let departmentCode = this.detailList.departmentCode;
      if (orgId && (!this.detailList.orgId || (id && id !== orgId))) {
        this.detailList.departmentDesc = nodeName;
        this.detailList.departmentCode = code;
        this.detailList.orgId = orgId;
        this.lastDepartmentCode = code;

        this.detailList.positionDesc = "";
        this.detailList.positionCode = "";
        this.detailList.jobCodeDesc = "";
        this.detailList.jobCode = "";

        this.detailList.supervisorName = "";
        this.detailList.supervisorEmployeeNo = "";
      }

      target.$emit("Close");
    }
  }
};
</script>
<style lang="less">
.emp-detail {
  min-height: 360px;
  overflow-x: hidden;
}
</style>
